<template>
    <eui-background type="common">
        <eui-navbar ref="EuiNavBar" title="店长视图" :displayable="false" @onClickStore="clickStore" rightIcon=""
            rightIcon5="icon-shaixuan" :showPopup="false" @clickRight="clickNavbarRight" />
        <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
            <scroll-view scroll-y="true" style="height: 100%">
                <eui-card title="销售总览" :titleDesc="`单位 ${uniTypeText}`">
                    <template v-slot:extra>
                        <view style="justify-content: flex-end;font-size: 26rpx;" @click="clickStore">
                            <span style="max-width: 200rpx; ">{{ sUserStoreName }} </span><span>></span>
                        </view>
                    </template>
                    <scroll-view
                        style="width:100%; -ms-overflow-style: none; scrollbar-width: thin; scrollbar-color: transparent transparent; "
                        scroll-x="true" show-scrollbar="false">
                        <eui-card-input v-model="formData.c_current_type" :range="currentTypeOpts" flexWrap="nowrap"
                            @buttonClick="currentTypeChange" titleWidth="0" placeholder="" h-padding="0"
                            radioWidth="175" alignType="left" type="radio" rightIconType="right"
                            :showBottomLine="false" />
                    </scroll-view>
                    <view style="width: 100%; display: grid;grid-template-columns: 33.33% 33.33% 33.33%;padding: 4rpx;">
                        <stat-item title="销售金额" :value="currentSum.c_at_sale" :compareValue="compareSum.c_at_sale"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="来客数" :value="currentSum.c_sale_count" :precision="0"
                            :compareValue="compareSum.c_sale_count" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="客单价(元)" :value="currentSum.c_atv" :compareValue="compareSum.c_atv"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="折扣金额" :value="currentSum.c_disc_value" :compareValue="compareSum.c_disc_value"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="毛利率(%)" :value="currentSum.c_gross_margin" method="rate"
                            :compareValue="compareSum.c_gross_margin" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="毛利额" :value="currentSum.c_gross_profit"
                            :compareValue="compareSum.c_gross_profit" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="会员销售金额" :value="currentSum.c_at_sale_mem"
                            :compareValue="compareSum.c_at_sale_mem" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="促销销售金额" :value="currentSum.c_at_sale_pro"
                            :compareValue="compareSum.c_at_sale_pro" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="促销毛利率(%)" :value="currentSum.c_gross_margin_pro" method="rate"
                            :compareValue="compareSum.c_gross_margin_pro" :compareTitle="compareTitle"></stat-item>
                        <stat-item title="日均库存金额" :value="currentSum.c_cost_inv" :compareValue="compareSum.c_cost_inv"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="库存周转天数" :value="currentSum.c_inv_days" :compareValue="compareSum.c_inv_days"
                            :compareTitle="compareTitle"></stat-item>
                        <stat-item title="投资回报率(%)" :value="currentSum.c_gmroi" :compareValue="compareSum.c_gmroi"
                            :compareTitle="compareTitle" method="rate"></stat-item>
                    </view>
                    <view
                        style="margin: 20rpx 0rpx; font-size: 20rpx; background-color: #F9FAFC; padding: 10rpx; color: #888888">
                        <view style="width: 100%; display: flex; flex-wrap: wrap;">
                            <view style="flex-grow: 0;">
                                <text style="color:red">●</text>
                                比较日期数据时，请确保使用相同的日期范围或天数，以保持一致性</br>
                            </view>
                            查看 <text style="color:#02B7E6;" @click="jumpCurSale">实时销售监测</text>
                            <view style="flex-grow: 0;">
                                本期 {{ formData.c_sale_da.substring(5, 12) }}({{
                                    dayOfWeek(formData.c_sale_da) }}) 至
                                {{ formData.c_sale_da_en.substring(5, 12) }}({{ dayOfWeek(formData.c_sale_da_en) }});对期
                                {{ formData.c_sale_da2.substring(5, 12) }}({{ dayOfWeek(formData.c_sale_da2) }}) 至
                                {{ formData.c_sale_da2_en.substring(5, 12) }}({{ dayOfWeek(formData.c_sale_da2_en) }})
                            </view>
                            <view style="flex-grow: 0;">
                                <text style="color:red">●</text>
                                <text v-if="sysConfig.rentSaleIsRevenue">包含租赁销售金额</text>
                                <text v-if="!sysConfig.rentSaleIsRevenue">不包含租赁销售金额</text>
                            </view>
                        </view>
                    </view>
                </eui-card>
                <eui-card title="销售排行" titleDesc="同区域同行业最多显示前20名">
                    <template v-slot:extra>
                        <view style="justify-content: flex-end;font-size: 26rpx;">
                            <eui-combox selectWidth="120rpx" v-model="formData.c_amount_type" valueColor="#666666"
                                backgroundColor="#F8F8F8" :border="false" :candidates="amountTypeOpts" fieldName="value"
                                @selectChange="onAmountTypeChange">
                            </eui-combox>
                        </view>
                    </template>
                    <view>本店排名第 <text :style="storeCurrentRank <= 3 ? 'color:red' : 'color:green'">{{ storeCurrentRank
                            }}</text>
                        ,同期排名第
                        <text :style="storeCurrentRank <= 3 ? 'color:red' : 'color:green'">{{ storeCompartRank }}</text>
                    </view>
                    <view>
                        <eui-lime-chart :option="saleRankChartOption" :chartStyle="saleRankChartStyle" />
                    </view>
                </eui-card>
                <eui-card title="部门销售" titleDesc="最多显示前20名">
                    <eui-tab :tabs="saleTabData" tabStyle="" :value="tabIndex3" @change="tabChange3" showBadge="true"
                        scroll-x="true" show-scrollbar="false">
                    </eui-tab>
                    <view v-if="tabIndex3 == 0">
                        <TableCard :column="storeColumn3" :listData="adnoTableData" :compareTable="true"
                            @clickCell="clickAdnoCell">
                        </TableCard>
                    </view>
                    <view v-if="tabIndex3 != 0">
                        <eui-lime-chart :option="adnoSaleChartOption" :chartStyle="adnoSaleChartStyle" />
                    </view>
                </eui-card>
                <eui-card :title="`部门销售${cardAdnoName}`" titleDesc="" v-if="showAdnoSale">
                    <template v-slot:extra>
                        <view style="justify-content: flex-end;font-size: 26rpx;color:#02B7E6;" @click="clickAdnoSale">
                            关闭
                        </view>
                    </template>
                    <eui-tab :tabs="saleTabData" tabStyle="" :value="tabIndex4" @change="tabChange4" showBadge="true"
                        scroll-x="true" show-scrollbar="false">
                    </eui-tab>
                    <view v-if="tabIndex4 == 0">
                        <TableCard :column="storeColumn4" :listData="adnoTableData2" :compareTable="true">
                        </TableCard>
                    </view>
                    <view v-if="tabIndex4 != 0">
                        <eui-lime-chart :option="adnoSaleChartOption2" :chartStyle="adnoSaleChartStyle2" />
                    </view>
                </eui-card>
                <eui-card :title="`异常汇总${cardAdnoName}`" titleDesc="">
                    <view style="width: 100%; display: grid;grid-template-columns: 33.33% 33.33% 33.33%;padding: 4rpx;">
                        <stat-item title="畅销缺货" :value="abnormalSummaryData.c_best_stockout" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="缺断货" :value="abnormalSummaryData.c_stockout" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="应销未订" :value="abnormalSummaryData.c_sale_not_order" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="进货未销" :value="abnormalSummaryData.c_purchase_not_sale" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="负毛利" :value="abnormalSummaryData.c_negative_gross_profit" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="负库存" :value="abnormalSummaryData.c_negative_stock" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="高库存" :value="abnormalSummaryData.c_tall_stock" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="滞销" :value="abnormalSummaryData.c_unsalable" :precision="0"
                            :showRate="false"></stat-item>
                        <stat-item title="未动销" :value="abnormalSummaryData.c_unsold_sales" :precision="0"
                            :showRate="false"></stat-item>
                    </view>
                </eui-card>
                <eui-card :title="`到货率${cardAdnoName}`" titleDesc="">
                    <view style="width: 100%; display: grid;grid-template-columns: 33.33% 33.33% 33.33%;padding: 4rpx;">
                        <stat-item title="整体到货率(%)" :value="arrivalRateData.c_whole_arrive_rate" method="original"
                            :compareValue="arrivalRateData.c_whole_direction" :precision="2"></stat-item>
                        <stat-item title="促销到货率(%)" :value="arrivalRateData.c_pro_arrive_rate" method="original"
                            :compareValue="arrivalRateData.c_pro_direction" :precision="2"></stat-item>
                        <stat-item title="新品到货率(%)" :value="arrivalRateData.c_new_arrive_rate" method="original"
                            :compareValue="arrivalRateData.c_new_direction" :precision="2"></stat-item>
                        <stat-item title="供应商(应/实)"
                            :value="`${arrivalRateData.c_whole_provider_num || 0}/${arrivalRateData.c_whole_provider_num_actual || 0}`"
                            :precision="0" :showRate="false"></stat-item>
                        <stat-item title="供应商(应/实)"
                            :value="`${arrivalRateData.c_pro_provider_num || 0}/${arrivalRateData.c_pro_provider_num_actual || 0}`"
                            :precision="0" :showRate="false"></stat-item>
                        <stat-item title="供应商(应/实)"
                            :value="`${arrivalRateData.c_new_provider_num || 0}/${arrivalRateData.c_new_provider_num_actual || 0}`"
                            :precision="0" :showRate="false"></stat-item>
                        <stat-item title="品种数(应/实)"
                            :value="`${arrivalRateData.c_whole_sku_num || 0}/${arrivalRateData.c_whole_sku_num_actual || 0}`"
                            :precision="0" :showRate="false"></stat-item>
                        <stat-item title="品种数(应/实)"
                            :value="`${arrivalRateData.c_pro_sku_num || 0}/${arrivalRateData.c_pro_sku_num_actual || 0}`"
                            :precision="0" :showRate="false"></stat-item>
                        <stat-item title="品种数(应/实)"
                            :value="`${arrivalRateData.c_new_sku_num || 0}/${arrivalRateData.c_new_sku_num_actual || 0}`"
                            :precision="0" :showRate="false"></stat-item>
                        <stat-item title="及时到货率(%)" :value="arrivalRateData.c_whole_promptly_arrive_rate" :precision="2"
                            :showRate="false"></stat-item>
                        <stat-item title="及时到货率(%)" :value="arrivalRateData.c_pro_promptly_arrive_rate" :precision="2"
                            :showRate="false"></stat-item>
                        <stat-item title="及时到货率(%)" :value="arrivalRateData.c_new_promptly_arrive_rate" :precision="2"
                            :showRate="false"></stat-item>
                    </view>
                </eui-card>
                <eui-card title="销售占比">
                    <eui-card-input v-model="formData.c_type" :range="saleRateOpts" @buttonClick="saleRateTypeChange"
                        titleWidth="0" radioWidth="200" placeholder="" h-padding="0" alignType="left" type="radio"
                        rightIconType="right" :showBottomLine="false" />
                    <view
                        style="width: 100%;display: grid;grid-template-columns: 30% 70%;  flex-wrap: wrap; padding: 4rpx;">
                        <view>
                            <eui-lime-chart :option="saleRateChartOption" :chartStyle="saleRateChartStyle" />
                        </view>
                        <view class="rate-view">
                            <view v-for="(item, index) in saleRateData" class="rate-card" style="height: 90rpx;">
                                <view class="rate-card" style="display: grid;grid-template-columns: 10% 50% 40%;">
                                    <eui-uicons style="margin-top: 10rpx;" size='20' fontFamily="enjoyIcon5"
                                        customPrefix="icon-xuanze_shixin" :color="rateColor[index]" />
                                    <text
                                        style="margin-left: 8rpx;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                        {{ item.title }}</text>
                                    <view style="margin-right: 2rpx;text-align: right;"
                                        :style="{ color: rateColor[index] }">{{
                                            item.rate
                                        }}</view>
                                </view>
                                <view class="rate-card" style="display: grid;grid-template-columns: 10% 90%;">
                                    <eui-uicons style="margin-top: 5rpx;margin-left: -2rpx;" size='25'
                                        fontFamily="enjoyIcon5"
                                        :customPrefix="item.upOrDown ? 'icon-shuju-shangsheng' : 'icon-shuju-xiajiang'"
                                        :color="item.upOrDown ? '#FF4000' : '#00AD60'" />
                                    <text
                                        style="margin-left: 8rpx;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{{
                                            numeral(item.value).format('0,0.00') }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </eui-card>
                <eui-card title="销售排名" titleDesc="最多显示前30名">
                    <eui-card-input v-model="formData.c_rank_type" :range="storeRankOpts" @buttonClick="rankTypeChange"
                        titleWidth="0" radioWidth="200" placeholder="" h-padding="0" alignType="left" type="radio"
                        rightIconType="right" :showBottomLine="false" />
                    <TableCard :column="rankColumn" :listData="saleRankTableData" :showIcon="true">
                    </TableCard>

                </eui-card>
            </scroll-view>
        </view>
    </eui-background>
    <eui-popup ref="customPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
        <view class="popup-content">
            <view class="popup-title">筛选</view>
            <eui-card-input v-model="formData.c_unit_type" :range="unitTypeOpts" title="显示单位" placeholder=""
                h-padding="0" alignType="left" type="radio" />
            <eui-card-input v-model="formData.c_adno_level" :range="sysConfig.adnoLevel" title="部门层级" h-padding="0"
                alignType="left" type="radio" />
            <!-- <eui-card-input v-model="showColumn" :range="columnOpts" title="显示指标"
                h-padding="0" alignType="left" type="multi" /> -->
        </view>
        <view class="bt-button">
            <eui-button type="max" single-tag="reset" title="重置" @buttonClick="customClick" />
            <eui-button type="max" single-tag="fix" title="确定" @buttonClick="customClick" />
        </view>
    </eui-popup>
    <eui-datetime-rangePicker :value="formData.c_sale_da" :c_plan_begin_time="formData.c_sale_da" type="date"
        :c_require_complete_time="formData.c_sale_da_en" :timeIndex="timeIndex" :visible="showDatePicker"
        :model="dateModel" :yearsArr="yearsArr" :isDark="false" title="选择日期" @cancel="handCancel"
        @confirm="handConfirm" />

    <!-- <eui-datetime-rangePicker :value="formData.c_plan_begin_time" :c_plan_begin_time="formData.c_plan_begin_time"
        :c_require_complete_time="formData.c_require_complete_time" :timeIndex="timeIndex" title="选择日期" 
        :visible="showDatePicker" :model="dateModel" :yearsArr="yearsArr" @cancel="handCancel" @confirm="handConfirm" /> -->

    <eui-datetime-rangePicker :value="formData.c_sale_da2" :c_plan_begin_time="formData.c_sale_da2" type="date"
        :c_require_complete_time="formData.c_sale_da2_en" :timeIndex="timeIndex" :visible="showDatePicker2"
        :model="dateModel" :yearsArr="yearsArr" :isDark="false" title="选择日期" @cancel="handCancel"
        @confirm="handConfirm2" />

    <eui-popup ref="searchPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
        <view class="popup-content">
            <view class="popup-title">自定义日期</view>
            <view class="m-card-input-view2">
                <view class="m-card-input-title2">
                    <text class="m-title-text2">本期日期</text>
                </view>
                <view class="time-view" @click="chooseTime(0)">
                    <text class="time-top">{{ formData.c_sale_da }}</text>
                </view>
                <view class="heng-view" />
                <view class="time-view" @click="chooseTime(1)">
                    <text class="time-top">{{ formData.c_sale_da_en }}</text>
                </view>
            </view>
            <view class="m-card-input-view2">
                <view class="m-card-input-title2">
                    <text class="m-title-text2">对期日期</text>
                </view>
                <view class="time-view" @click="chooseTime2(0)">
                    <text class="time-top">{{ formData.c_sale_da2 }}</text>
                </view>
                <view class="heng-view" />
                <view class="time-view" @click="chooseTime2(1)">
                    <text class="time-top">{{ formData.c_sale_da2_en }}</text>
                </view>
            </view>
        </view>
        <view class="bt-button">
            <eui-button type="max" single-tag="reset" title="重置" @buttonClick="buttonClick" />
            <eui-button type="max" single-tag="fix" title="确定" @buttonClick="buttonClick" />
        </view>
    </eui-popup>

    <eui-popup ref="storePopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
        <view class="popup-content">
            <view class="popup-title">门店列表</view>
            <scroll-view scroll-y="true"
                style="width: 100%;min-height: 10px;max-height:400px;box-sizing: border-box;overflow-y: scroll;">
                <view v-for="(item, index) in storeData" :key="index">
                    <eui-text :value="item" :name="getRelatedName('rdsStores', item)" type="titlename"
                        :title="index + 1 + '. ' + ''" />
                </view>
            </scroll-view>
        </view>
        <view class="bt-button">
            <eui-button type="max" single-tag="close" title="关闭" @buttonClick="buttonClick" />
        </view>
    </eui-popup>

</template>

<script setup type="ts">
import { onMounted, ref, reactive, computed, watch } from "vue";
import service from "@/common/service";
import { getRdsUrl, rdsRequest, } from '@/hooks/rdsServices';
import dateRangUtil from "@/common/dateRangUtil";
import datetimePicker from '../TaskWork/components/datetime-picker/datetime-picker.vue';
import { onLoad } from "@dcloudio/uni-app";
import { init, getRdsSysConfig } from '@/hooks/init';
import { validateStores, validateGds, defaultMapping, validateStoresAndWno } from '@/hooks/useValidateMethod';
import StatItem from "./StatItem.vue";
import { useMainStore } from "@/store/modules/store";
import TableCard from '@/components/TableCard.vue';
import Enjoy from "@/common/enjoy";
import dayjs from 'dayjs';
import { getRelatedName, getUserDictName, getDictName } from '../components/RelatedName.js';
import { useProRelatedNameHook } from '@/hooks/useProRelatedName';
import { usePayCodeHook } from '@/hooks/usePayCode';
import numeral from 'numeral';

const { payCodeItems, payClassItems } = usePayCodeHook();
const { mapChannel } = useProRelatedNameHook();

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();

const searchPopup = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const listHeight = ref(300);
const oriHeight = ref(300);

const customPopup = ref(null);

const showDatePicker = ref(false);
const showDatePicker2 = ref(false);
const dateModel = ref(['year', 'month', 'day']);
const yearsArr = ref([dayjs().year() - 10, dayjs().year()]);
const timeIndex = ref(0);

const showColumn = ref([]);
dayjs.locale({
    ...dayjs.Ls['en'], // 以英文本地化配置为基础
    weekStart: 1 // 将每周的起始日设置为周一（0 代表周日，1 代表周一）
});
// 选择时间-取消
const handCancel = () => {
    showDatePicker.value = false;
    showDatePicker2.value = false;
}
// 选择时间-确认
const handConfirm = (time1, time2) => {
    showDatePicker.value = false;
    if (time2 < time1) {
        formData.value.c_sale_da = time2.substring(0, 10);
        formData.value.c_sale_da_en = time2.substring(0, 10);
        return;
    }
    if (time1) {
        formData.value.c_sale_da = time1.substring(0, 10);
    }
    if (time2) {
        formData.value.c_sale_da_en = time2.substring(0, 10);
    }
}
// 选择时间-确认
const handConfirm2 = (time1, time2) => {
    showDatePicker2.value = false;
    if (time2 < time1) {
        formData.value.c_sale_da2 = time2.substring(0, 10);
        formData.value.c_sale_da2_en = time2.substring(0, 10);
        return;
    }
    if (time1) {
        formData.value.c_sale_da2 = time1.substring(0, 10);
    }
    if (time2) {
        formData.value.c_sale_da2_en = time2.substring(0, 10);
    }
}
// 选择时间
const chooseTime = (index) => {
    timeIndex.value = index;
    setTimeout(() => {
        showDatePicker.value = true;
    }, 200)
}
const chooseTime2 = (index) => {
    timeIndex.value = index;
    setTimeout(() => {
        showDatePicker2.value = true;
    }, 200)
}

// 查询表单
const formData = ref({
    c_current_type: '1',
    c_sale_da: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),
    c_sale_da_en: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),
    c_sale_da2: dayjs().subtract(8, 'days').format('YYYY-MM-DD'),//对期
    c_sale_da2_en: dayjs().subtract(8, 'days').format('YYYY-MM-DD'),//对期
    c_is_compare: true,  //比上周
    c_type: '6', //1-机构, 2-部门, 3-品类
    c_level: 1,
    c_adno_level: 1, //部门层级
    c_class_level: 1, //品类层级
    c_store_id: mainStore.loginInfo.sUserStore,
    c_p_id: '',
    c_unit_type: '1',
    c_amount_type: 'c_sale_gradation',
    c_rank_type: '1',//排名类型
    c_day_period: '1',//昨日全天
})
const saleTabData = ref([{ name: '实绩对比' }, { name: '销售排名' }, { name: '毛利排名' }, { name: '销售增减排名' }, { name: '毛利增减排名' }]);

const tabIndex3 = ref(0);
const tabChange3 = async (value) => {
    tabIndex3.value = value;
    let column = 'c_at_sale';
    if (tabIndex3.value == 2) {
        column = 'c_gross_profit';
    } else if (tabIndex3.value == 3) {
        column = 'c_sale_gradation';
    } else if (tabIndex3.value == 4) {
        column = 'c_gross_profit_gradation';
    }
    await formatAdnoSaleChartData(column);
}
const tabIndex4 = ref(0);
const tabChange4 = async (value) => {
    tabIndex4.value = value;
    let column = 'c_at_sale';
    if (tabIndex4.value == 2) {
        column = 'c_gross_profit';
    } else if (tabIndex4.value == 3) {
        column = 'c_sale_gradation';
    } else if (tabIndex4.value == 4) {
        column = 'c_gross_profit_gradation';
    }
    await formatAdnoSaleChartData2(column);

}

const storeType = ref('0');
const updateStoreType = async () => {
    // const result = await validateStores(
    //     { fieldName: 'c_store_id', newValue: formData.value.c_store_id },
    //     { ischecklimit: true, firstValueMode: true }
    // );
    // console.log('updateStoreType', result);
    // storeType.value = result?.c_type || 0;
    // saleRateOpts[0].disabled = !['0', '1'].includes(storeType.value)
    storeType.value = 0;
}

onMounted(async () => {
    await updateStoreType();
})
// 单位类型
const unitTypeOpts = reactive([
    { text: '元', value: '1' },
    { text: '万元', value: '2' }
])
const uniTypeText = computed(() => `${unitTypeOpts.find(f => f.value == formData.value.c_unit_type)?.text}`)

const columnOpts = reactive([
    { text: '交易笔数', value: 'c_sale_count' },
    { text: '客单价', value: 'c_atv' },
    { text: '销售占比', value: 'c_sale_rate' },
    { text: '毛利占比', value: 'c_gross_profit_rate' },
    { text: '库存金额', value: 'c_cost_inv' },
    { text: '周转天数', value: 'c_inv_days' },
])
const columnOptsText = computed(() => `${columOpts.find(f => f.value == showColumn.value)?.text}`)


const amountTypeOpts = reactive([
    { text: '销售额', value: 'c_sale_gradation' },
    { text: '毛利额', value: 'c_gross_profit_gradation' },
    // { text: '毛利率', value: 'c_gross_margin_gradation' }
])
const onAmountTypeChange = async (value) => {
    await formatSaleRankChartData();
}
// 顶部统计
const currentTypeOpts = reactive([
    { text: '昨日/环期', value: '1' },
    { text: '本周/上周', value: '2' },
    { text: '本月/上月', value: '3' },
    { text: '自定义', value: '4' }
])
const currentTitle = computed(() => `${currentTypeOpts.find(f => f.value == formData.value.c_current_type)?.text}销售`)
// 变更时间类型
const currentTypeChange = async (value) => {
    if (value === '1') {
        //昨日
        formData.value.c_sale_da = dayjs().subtract(1, 'days').format('YYYY-MM-DD');
        formData.value.c_sale_da_en = dayjs().subtract(1, 'days').format('YYYY-MM-DD');
        // const periodDate = getSequentialDatesLastPeriod(formData.value.c_sale_da, formData.value.c_sale_da_en);

        // //环期
        formData.value.c_sale_da2 = dayjs().subtract(8, 'days').format('YYYY-MM-DD');
        formData.value.c_sale_da2_en = dayjs().subtract(8, 'days').format('YYYY-MM-DD');

    } else if (value === '2') {
        if (dayjs().day() === 1) {
            // 获取上周的第一天
            let firstDay = dayjs().subtract(7, 'days').startOf('week').format('YYYY-MM-DD');
            // 获取上周的最后一天
            let lastDay = dayjs().subtract(7, 'days').endOf('week').format('YYYY-MM-DD');
            formData.value.c_sale_da = firstDay;
            formData.value.c_sale_da_en = lastDay;
            //上周开始
            formData.value.c_sale_da2 = dayjs(firstDay).subtract(1, 'weeks').format('YYYY-MM-DD');
            //上周结束
            formData.value.c_sale_da2_en = dayjs(lastDay).subtract(1, 'weeks').format('YYYY-MM-DD');
        } else {
            // 获取本周的第一天
            let firstDay = dayjs().startOf('week').format('YYYY-MM-DD');
            // 获取昨天的日期
            let yestaday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');

            formData.value.c_sale_da = firstDay;
            formData.value.c_sale_da_en = yestaday;
            //上周开始
            formData.value.c_sale_da2 = dayjs(firstDay).subtract(1, 'weeks').format('YYYY-MM-DD');
            //上周结束
            formData.value.c_sale_da2_en = dayjs(yestaday).subtract(1, 'weeks').format('YYYY-MM-DD');
        }

    } else if (value === '3') {
        if (dayjs().date() === 1) {
            // 获取上月的第一天
            let firstDay = dayjs().subtract(1, 'months').startOf('month').format('YYYY-MM-DD');
            // 获取上月的最后一天
            let lastDay = dayjs().subtract(1, 'months').endOf('month').format('YYYY-MM-DD');
            formData.value.c_sale_da = firstDay;
            formData.value.c_sale_da_en = lastDay;
            //上月开始
            formData.value.c_sale_da2 = dayjs(firstDay).subtract(1, 'months').format('YYYY-MM-DD');
            //上月结束
            formData.value.c_sale_da2_en = dayjs(lastDay).subtract(1, 'months').format('YYYY-MM-DD');
        } else {
            // 获取本月的第一天
            let firstDay = dayjs().startOf('month').format('YYYY-MM-DD');
            // 获取昨天的日期
            let yestaday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');

            formData.value.c_sale_da = firstDay;
            formData.value.c_sale_da_en = yestaday;

            //上月开始
            formData.value.c_sale_da2 = dayjs(firstDay).subtract(1, 'months').format('YYYY-MM-DD');
            //上月结束
            formData.value.c_sale_da2_en = dayjs(yestaday).subtract(1, 'months').format('YYYY-MM-DD');
        }

    } else if (value === '4') {
        searchPopup.value.open();
        return;
    }
    await searchData();
}


const saleRateOpts = reactive([
    { text: '渠道', value: '6' },
    { text: '经营方式', value: '9' },
    { text: '支付方式', value: '10' }
])
const saleRateChartTitle = computed(() => `${saleRateOpts.find(f => f.value == formData.value.c_type)?.text}占比`)

// 顶部统计
const storeRankOpts = reactive([
    { text: '品类', value: '1' },
    { text: '品牌', value: '2' },
    { text: '商品', value: '3' }
])
const storeRankChartTitle = computed(() => `${storeRankOpts.find(f => f.value == formData.value.c_type)?.text}排名`)

const rankTypeChange = async (value) => {
    formData.value.c_rank_type = value;
    service.enjoyShowLoading("正在加载...");
    await querySaleStoreRankTable();
    service.enjoyHideLoading();
}


const compareTitle = computed(() => {
    const name = currentTypeOpts.find(f => f.value == formData.value.c_current_type)?.text;
    let chartName = name.split('/')[1];
    if (formData.value.c_current_type === '4') {
        chartName = '对期';
    }
    return chartName;
})

const dayOfWeek = (value) => {
    if (value) {
        const dayIndex = dayjs(value).day();
        const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return daysOfWeek[dayIndex];
    }
    return '';
}

const saleRateTypeChange = async (value) => {
    service.enjoyShowLoading("正在加载...");
    if (value == '2') {
        formData.value.c_level = formData.value.c_adno_level;
    } else if (value == '3') {
        formData.value.c_level = formData.value.c_class_level;
    }
    formData.value.c_type = value;
    await querySaleRate();
    service.enjoyHideLoading();
}

const saleRateChartDataY = ref([])
const saleRateChartDataX = ref([]);
const saleRateChartStyle = ref("height: 300rpx;background: #FFFFFF");
const rateColor = ref(['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']);
const saleRateChartOption = computed(() => {
    return {
        title: {
            text: saleRateChartTitle.value,
            bottom: '0%',
            left: '8%',
            textStyle: {
                fontSize: 12,
                color: '#666666'
            }
        },
        // grid: {
        //     left: '3%',
        //     right: '4%',
        //     bottom: '3%',
        //     top: '4%',
        //     containLabel: true,
        // },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'none'
        },
        legend: {
            show: false,
            top: '0%',
            left: 'center'
        },
        series: saleRateChartDataY.value,
    }
});

// 查询数据接口
const searchData = async () => {
    service.enjoyShowLoading('正在加载...');
    //销售总览
    queryCurSale();
    //销售排名
    querySaleStoreRank();
    //部门销售
    queryAdnoSale();
    //异常汇总
    queryAbnormalSummary();
    //到货率
    queryArrivalRate();
    //销售占比
    querySaleRate();
    //销售排名
    querySaleStoreRankTable();
    setTimeout(() => {
        service.enjoyHideLoading();
    }, 2000)
}

//销售总览
const currentData = ref([])
const compareData = ref([])
const queryCurSale = async () => {
    const objectData = {
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_is_compare: true,
    };
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'QueryStoreViewMBM', objectData, '881',);
    currentData.value = result?.currentData;
    compareData.value = result?.compareData;
}

const currentSum = computed(() => {
    return calcSum(currentData.value);
})
const compareSum = computed(() => {
    return calcSum(compareData.value);
})


const rankData = ref([]);
//销售排名
const querySaleStoreRank = async () => {
    const objectData = {
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        // c_p_id: formData.value.c_p_id,
        // c_level: formData.value.c_level + 1 || 1,
    };

    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'QueryStoreViewRankMBM', objectData, '881');
    rankData.value = result;
    await formatSaleRankChartData(result);
}

const saleRankChartDataX = ref([]);
const saleRankChartDataY = ref([]);
const saleRankChartStyle = ref("height: 1000rpx;background: #FFFFFF");
const saleRankChartOption = computed(() => {
    return {
        title: {
            text: ''
        },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            triggerOn: 'click',
        },
        legend: {
            top: '0%',
            itemHeight: 8,
        },
        grid: {
            left: '0%',
            right: '0%',
            bottom: '3%',
            top: '4%',
            containLabel: true
        },
        xAxis: {
            boundaryGap: [0, 0.01],
            width: 20,
            splitLine: {
                show: false // 不显示网格线
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            axisLabel: {
                rotate: 45
            },
            type: 'value',
        },
        yAxis: {
            type: 'category',
            axisLabel: {
                rotate: 45,
                formatter: function (value) {
                    if (value === getRelatedName("rdsStores", formData.value.c_store_id)) {
                        return '{a|' + value + '}';
                    } else {
                        return value;
                    }
                },
                rich: {
                    a: {
                        color: 'red'
                    }
                }
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            data: saleRankChartDataX.value
        },
        series: saleRankChartDataY.value,
    }
});

const storeCurrentRank = ref(0);
const storeCompartRank = ref(0);
const formatSaleRankChartData = async () => {
    saleRankChartDataY.value = [];
    const amountType = formData.value.c_amount_type || 'c_sale_gradation';

    const storeRankData = rankData.value.map(x => {
        return {
            ...x,
            c_sale_gradation: (x.c_sale_gradation * 100).toFixed(2),
            c_gross_profit_gradation: (x.c_gross_profit_gradation * 100).toFixed(2),
            c_at_sale: (x.c_sale_gradation * 100).toFixed(2),
            c_gross_profit: (x.c_gross_profit_gradation * 100).toFixed(2),
        }
    })

    //从大到小排序
    storeRankData.sort((a, b) => b[amountType] - a[amountType]);

    //截取前20名
    let sortedData = storeRankData.sort((a, b) => b[amountType] - a[amountType]).slice(0, 20);

    //排名
    if (amountType == 'c_sale_gradation') {
        storeCurrentRank.value = storeRankData.find(x => x.c_store_id == formData.value.c_store_id).c_sale_current_rank;
        storeCompartRank.value = storeRankData.find(x => x.c_store_id == formData.value.c_store_id).c_sale_compare_rank;
    } else {
        storeCurrentRank.value = storeRankData.find(x => x.c_store_id == formData.value.c_store_id).c_gross_profit_current_rank;
        storeCompartRank.value = storeRankData.find(x => x.c_store_id == formData.value.c_store_id).c_gross_profit_compare_rank;
    }

    //从小到大排序
    sortedData = storeRankData.sort((a, b) => a[amountType] - b[amountType]);
    const saleCurrentItemSort = sortedData.map(x => x[amountType]);
    saleRankChartDataX.value = storeRankData.map(x => getRelatedName("rdsStores", x.c_store_id) || x.c_store_id);
    saleRankChartDataY.value.push({
        name: amountTypeOpts.find(f => f.value == amountType)?.text,
        type: 'bar',
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleCurrentItemSort,
        // barWidth: '50%',
        label: {
            show: true, // 显示标签
            distance: 3,
            borderWidth: 100,
            position: ['50%', '50%'], // 标签位置
            formatter: '{c}' + '%', // {c} 表示数据值
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
    // 计算平均值
    const sum = saleCurrentItemSort.reduce((p, v) => Number(p) + Number(v), 0);
    const saleAvg = Array(saleCurrentItemSort.length).fill((sum / saleCurrentItemSort.length).toFixed(2));
    saleRankChartDataY.value.push({
        name: '平均值',
        type: 'line',
        smooth: true,
        showSymbol: false,
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleAvg,
        barWidth: '100%',
        lineStyle: {
            type: 'dashed' //虚线
        },
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            // 可以通过 formatter 自定义标签格式
            // formatter: bcnameList[i] + '\n' + '{c}' + '%', // {c} 表示数据值
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
}

const storeColumn3 = ref([
    {
        title: '部门', // th标题
        isFixed: true, // 是否固定
        key: 'c_adno_name', // 对应字段，
        align: 'left',
        width: 0.8, // 宽度 width * 100 rpx
        color: '#02B7E6',
    },
    {
        title: '销售金额', // th标题
        isFixed: false, // 是否固定
        key: 'c_at_sale', // 对应字段
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
        //slot: 'b' // 插槽名
    },
    {
        title: '毛利额', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '毛利率(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_margin', // 对应字段
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
        //slot: 'c' // 插槽名
    },
    {
        title: '交易笔数', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_count',
        align: 'right',
        width: 1.5,
        compare: true,
    },
    {
        title: '客单价(元)', // th标题
        isFixed: false, // 是否固定
        key: 'c_atv',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '销售占比(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_rate',
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
    },
    {
        title: '毛利占比(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit_rate',
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
    },
    {
        title: '库存金额', // th标题
        isFixed: false, // 是否固定
        key: 'c_cost_inv',
        align: 'right',
        width: 2,
        compare: true,
        precision: 2,
    },
    {
        title: '周转天数', // th标题
        isFixed: false, // 是否固定
        key: 'c_inv_days',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '渗透率(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_perm',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
]);

const storeColumn4 = ref([
    {
        title: '部门', // th标题
        isFixed: true, // 是否固定
        key: 'c_adno_name', // 对应字段，
        align: 'left',
        width: 0.8, // 宽度 width * 100 rpx
    },
    {
        title: '销售金额', // th标题
        isFixed: false, // 是否固定
        key: 'c_at_sale', // 对应字段
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
        //slot: 'b' // 插槽名
    },
    {
        title: '毛利额', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '毛利率(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_margin', // 对应字段
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
        //slot: 'c' // 插槽名
    },
    {
        title: '交易笔数', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_count',
        align: 'right',
        width: 1.5,
        compare: true,
    },
    {
        title: '客单价(元)', // th标题
        isFixed: false, // 是否固定
        key: 'c_atv',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '销售占比(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_rate',
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
    },
    {
        title: '毛利占比(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit_rate',
        align: 'right',
        width: 1.8,
        compare: true,
        precision: 2,
    },
    {
        title: '库存金额', // th标题
        isFixed: false, // 是否固定
        key: 'c_cost_inv',
        align: 'right',
        width: 2,
        compare: true,
        precision: 2,
    },
    {
        title: '周转天数', // th标题
        isFixed: false, // 是否固定
        key: 'c_inv_days',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
    {
        title: '渗透率(%)', // th标题
        isFixed: false, // 是否固定
        key: 'c_perm',
        align: 'right',
        width: 1.5,
        compare: true,
        precision: 2,
    },
]);

//部门数据
const currentAdnoSale = ref([])
const compareAdnoSale = ref([])
const queryAdnoSale = async () => {
    const objectData = {
        ...formData.value,
        c_level: formData.value.c_level || '1',
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_is_compare: true
    }
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'QueryStoreViewAdnoMBM', objectData, '881');
    currentAdnoSale.value = result?.currentData.filter(x => x.c_at_sale != 0 || x.c_sale_count != 0 || x.c_cost_inv != 0);
    compareAdnoSale.value = result?.compareData.filter(x => x.c_at_sale != 0 || x.c_sale_count != 0 || x.c_cost_inv != 0);
    await formatAdnoSaleTableData();
    await formatAdnoSaleChartData();
}

const adnoTableData = ref([]);
const formatAdnoSaleTableData = async () => {
    let ids = [...currentAdnoSale.value?.map(f => f.c_id), ...compareAdnoSale.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);

    const list = ids.map(x => {
        const current = currentAdnoSale.value.find(f => f.c_id == x) || {};
        const compare = compareAdnoSale.value.find(f => f.c_id == x) || {};
        const c_sale_rate_currrent = current?.c_at_sale_sj == 0 ? 0 : (Math.round((current?.c_at_sale / current?.c_at_sale_sj) * 10000) / 100).toFixed(2);
        const c_gross_profit_rate_currrent = current?.c_gross_profit_sj == 0 ? 0 : (Math.round((current?.c_gross_profit / current?.c_gross_profit_sj) * 10000) / 100).toFixed(2);
        const c_perm_currrent = current?.c_sale_count_sj == 0 ? 0 : (Math.round((current?.c_sale_count / current?.c_sale_count_sj) * 10000) / 100).toFixed(2);

        const c_sale_rate_compare = compare?.c_at_sale_sj == 0 ? 0 : Math.round(((compare?.c_at_sale / compare?.c_at_sale_sj) * 10000) / 100).toFixed(2);
        const c_gross_profit_rate_compare = compare?.c_gross_profit_sj == 0 ? 0 : (Math.round((compare?.c_gross_profit / compare?.c_gross_profit_sj) * 10000) / 100).toFixed(2);
        const c_perm_compare = compare?.c_sale_count_sj == 0 ? 0 : (Math.round((compare?.c_sale_count / compare?.c_sale_count_sj) * 10000) / 100).toFixed(2);

        return {
            title: getRelatedName("rdsDeparts", x) || x,
            current: { ...(calcUnit(current || { ...defaultSum })), c_adno_name: getRelatedName("rdsDeparts", x) || x, c_sale_rate: c_sale_rate_currrent, c_gross_profit_rate: c_gross_profit_rate_currrent, c_perm: c_perm_currrent },
            compare: { ...(calcUnit(compare || { ...defaultSum })), c_adno_name: getRelatedName("rdsDeparts", x) || x, c_sale_rate: c_sale_rate_compare, c_gross_profit_rate: c_gross_profit_rate_compare, c_perm: c_perm_compare },
            option: {
                c_at_sale: !compare.c_at_sale ? 0 : (current.c_at_sale - compare.c_at_sale) / compare.c_at_sale * 100,
                c_gross_profit: !compare.c_gross_profit ? 0 : (current.c_gross_profit - compare.c_gross_profit) / compare.c_gross_profit * 100,
                c_gross_margin: (current.c_gross_margin - compare.c_gross_margin),
                c_sale_count: !compare.c_sale_count ? 0 : (current.c_sale_count - compare.c_sale_count) / compare.c_sale_count * 100,
                c_atv: !compare.c_atv ? 0 : (current.c_atv - compare.c_atv) / compare.c_atv * 100,
                c_sale_rate: (c_sale_rate_currrent - c_sale_rate_compare),
                c_gross_profit_rate: (c_gross_profit_rate_currrent - c_gross_profit_rate_compare),
                c_cost_inv: !compare.c_cost_inv ? 0 : (current.c_cost_inv - compare.c_cost_inv) / compare.c_cost_inv * 100,
                c_inv_days: !compare.c_inv_days ? 0 : (current.c_inv_days - compare.c_inv_days) / compare.c_inv_days * 100,
                c_perm: (c_perm_currrent - c_perm_compare),
            }
        }
    })

    const currentSum = calcSum(currentAdnoSale.value);
    const compareSum = calcSum(compareAdnoSale.value);

    // 添加全部
    list?.push({
        title: '全部部门',
        current: { ...currentSum, c_adno_name: '全部部门', c_sale_rate: 100, c_gross_profit_rate: 100, c_perm: 100 },
        compare: { ...compareSum, c_adno_name: '全部部门', c_sale_rate: 100, c_gross_profit_rate: 100, c_perm: 100 },
        option: {
            c_at_sale: !compareSum.c_at_sale ? 0 : (currentSum.c_at_sale - compareSum.c_at_sale) / compareSum.c_at_sale,
            c_gross_profit: !compareSum.c_gross_profit ? 0 : (currentSum.c_gross_profit - compareSum.c_gross_profit) / compareSum.c_gross_profit,
            c_gross_margin: (currentSum.c_gross_margin - compareSum.c_gross_margin),
            c_sale_count: !compareSum.c_sale_count ? 0 : (currentSum.c_sale_count - compareSum.c_sale_count) / compareSum.c_sale_count,
            c_atv: !compareSum.c_atv ? 0 : (currentSum.c_atv - compareSum.c_atv) / compareSum.c_atv,
            c_sale_rate: (currentSum.c_sale_rate - compareSum.c_sale_rate),
            c_gross_profit_rate: (currentSum.c_gross_profit_rate - compareSum.c_gross_profit_rate),
            c_cost_inv: !compareSum.c_cost_inv ? 0 : (currentSum.c_cost_inv - compareSum.c_cost_inv) / compareSum.c_cost_inv,
            c_inv_days: !compareSum.c_inv_days ? 0 : (currentSum.c_inv_days - compareSum.c_inv_days) / compareSum.c_inv_days,
            c_perm: (currentSum.c_perm - compareSum.c_perm),
        }
    });
    adnoTableData.value = list
}

const adnoSaleChartDataY = ref([])
const adnoSaleChartDataX = ref([]);
const adnoSaleChartStyle = ref("height: 1000rpx;background: #FFFFFF");
const adnoSaleChartOption = computed(() => {
    return {
        title: {
            text: ''
        },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            triggerOn: 'click',
        },
        legend: {
            top: '0%',
            itemHeight: 8,
        },
        grid: {
            left: '0%',
            right: '0%',
            bottom: '3%',
            top: '4%',
            containLabel: true
        },
        xAxis: {
            boundaryGap: [0, 0.01],
            width: 20,
            splitLine: {
                show: false // 不显示网格线
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            axisLabel: {
                rotate: 45
            },
            type: 'value',
        },
        yAxis: {
            type: 'category',
            axisLabel: {
                rotate: 45,
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            data: adnoSaleChartDataX.value
        },
        series: adnoSaleChartDataY.value,
    }
});

const formatAdnoSaleChartData = async (type = 'c_at_sale') => {
    adnoSaleChartDataY.value = [];
    const amountType = type;
    let ids = [...currentAdnoSale.value?.map(f => f.c_id), ...compareAdnoSale.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);
    const list = ids.map(x => {
        const current = currentAdnoSale.value.find(f => f.c_id == x) || {};
        const compare = compareAdnoSale.value.find(f => f.c_id == x) || {};

        const c_sale_gradation = compare.c_at_sale == 0 ? 0 : ((current?.c_at_sale - compare.c_at_sale) / compare.c_at_sale * 100 || 0).toFixed(2);
        const c_gross_profit_gradation = compare.c_gross_profit == 0 ? 0 : ((current?.c_gross_profit - compare.c_gross_profit) / compare.c_gross_profit * 100 || 0).toFixed(2);

        return {
            title: getRelatedName("rdsDeparts", x) || x,
            current: { ...(calcUnit(current || { ...defaultSum })), c_sale_gradation: c_sale_gradation, c_gross_profit_gradation: c_gross_profit_gradation },
            compare: { ...(calcUnit(compare || { ...defaultSum })), c_sale_gradation: c_sale_gradation, c_gross_profit_gradation: c_gross_profit_gradation },
        }
    })

    //先从大到小排序，取前10个
    let sortedData = list.sort((a, b) => b.current[amountType] - a.current[amountType]).slice(0, 20);
    sortedData = list.sort((a, b) => a.current[amountType] - b.current[amountType]);
    const saleCurrentItemSort = sortedData.map(x => parseFloat(x.current[amountType]).toFixed(2));
    const saleCompareItemSort = sortedData.map(x => parseFloat(x.compare[amountType]).toFixed(2));
    adnoSaleChartDataX.value = sortedData.map(x => x.title);
    adnoSaleChartDataY.value.push({
        name: '本期',//+amountTypeOpts.find(f => f.value == amountType)?.text,
        type: 'bar',
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleCurrentItemSort,
        // barWidth: '50%',
        label: {
            show: true, // 显示标签
            distance: 3,
            borderWidth: 100,
            position: ['50%', '50%'], // 标签位置
            formatter: function (params) {
                if ([1, 2].includes(tabIndex3.value)) {
                    return numeral(params.data).format('0,0.00')
                } else {
                    return params.data + '%'
                }
            },
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
    if ([1, 2].includes(tabIndex3.value)) {
        adnoSaleChartDataY.value.push({
            name: '对期',//+amountTypeOpts.find(f => f.value == amountType)?.text,
            type: 'bar',
            emphasis: {
                focus: 'none',
                disabled: true,
            },
            data: saleCompareItemSort,
            // barWidth: '50%',
            label: {
                show: true, // 显示标签
                distance: 3,
                borderWidth: 100,
                position: ['50%', '50%'], // 标签位置
                formatter: function (params) {
                    return numeral(params.data).format('0,0.00')
                },
                color: "#FFFFFF",
                lineHeight: 12,
                fontSize: 10,
                fontWeight: 100,
                align: 'center',
                verticalAlign: 'middle'
            }
        })
    }
    // 计算平均值
    const sum = saleCurrentItemSort.reduce((p, v) => Number(p) + Number(v), 0);
    const saleAvg = Array(saleCurrentItemSort.length).fill((sum / saleCurrentItemSort.length).toFixed(2));
    adnoSaleChartDataY.value.push({
        name: '平均值',
        type: 'line',
        smooth: true,
        showSymbol: false,
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleAvg,
        barWidth: '100%',
        lineStyle: {
            type: 'dashed' //虚线
        },
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            // 可以通过 formatter 自定义标签格式
            // formatter: bcnameList[i] + '\n' + '{c}' + '%', // {c} 表示数据值
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })

}

//二级部门数据
const currentAdnoSale2 = ref([])
const compareAdnoSale2 = ref([])
const queryAdnoSale2 = async () => {
    const objectData = {
        ...formData.value,
        c_level: formData.value.c_level + 1 || 1,
        c_p_id: formData.value.c_p_id,
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_is_compare: true
    }
    //时段数据
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'QueryStoreViewAdnoMBM', objectData, '881');
    currentAdnoSale2.value = result?.currentData.filter(x => x.c_at_sale != 0 || x.c_sale_count != 0 || x.c_cost_inv != 0);
    compareAdnoSale2.value = result?.compareData.filter(x => x.c_at_sale != 0 || x.c_sale_count != 0 || x.c_cost_inv != 0);
    await formatAdnoSaleTableData2();
    await formatAdnoSaleChartData2();
}

const adnoTableData2 = ref([]);
const formatAdnoSaleTableData2 = async () => {
    let ids = [...currentAdnoSale2.value?.map(f => f.c_id), ...compareAdnoSale2.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);

    const list = ids.map(x => {
        const current = currentAdnoSale2.value.find(f => f.c_id == x) || {};
        const compare = compareAdnoSale2.value.find(f => f.c_id == x) || {};

        const c_sale_rate_currrent = current?.c_at_sale_sj == 0 ? 0 : Math.round(((current?.c_at_sale / current?.c_at_sale_sj) * 10000) / 100).toFixed(2);
        const c_gross_profit_rate_currrent = current?.c_gross_profit_sj == 0 ? 0 : Math.round(((current?.c_gross_profit / current?.c_gross_profit_sj) * 10000) / 100).toFixed(2);
        const c_perm_currrent = current?.c_sale_count_sj == 0 ? 0 : Math.round(((current?.c_sale_count / current?.c_sale_count_sj) * 10000) / 100).toFixed(2);

        const c_sale_rate_compare = compare?.c_at_sale_sj == 0 ? 0 : Math.round(((compare?.c_at_sale / compare?.c_at_sale_sj) * 10000) / 100).toFixed(2);
        const c_gross_profit_rate_compare = compare?.c_gross_profit_sj == 0 ? 0 : Math.round(((compare?.c_gross_profit / compare?.c_gross_profit_sj) * 10000) / 100).toFixed(2);
        const c_perm_compare = compare?.c_sale_count_sj == 0 ? 0 : Math.round(((compare?.c_sale_count / compare?.c_sale_count_sj) * 10000) / 100).toFixed(2);

        return {
            title: getRelatedName("rdsDeparts", x) || x,
            current: { ...(calcUnit(current || { ...defaultSum })), c_adno_name: getRelatedName("rdsDeparts", x) || x, c_sale_rate: c_sale_rate_currrent, c_gross_profit_rate: c_gross_profit_rate_currrent, c_perm: c_perm_currrent },
            compare: { ...(calcUnit(compare || { ...defaultSum })), c_adno_name: getRelatedName("rdsDeparts", x) || x, c_sale_rate: c_sale_rate_compare, c_gross_profit_rate: c_gross_profit_rate_compare, c_perm: c_perm_compare },
            option: {
                c_at_sale: !compare.c_at_sale ? 0 : (current.c_at_sale - compare.c_at_sale) / compare.c_at_sale * 100,
                c_gross_profit: !compare.c_gross_profit ? 0 : (current.c_gross_profit - compare.c_gross_profit) / compare.c_gross_profit * 100,
                c_gross_margin: (current.c_gross_margin - compare.c_gross_margin) * 100,
                c_sale_count: !compare.c_sale_count ? 0 : (current.c_sale_count - compare.c_sale_count) / compare.c_sale_count * 100,
                c_atv: !compare.c_atv ? 0 : (current.c_atv - compare.c_atv) / compare.c_atv * 100,
                c_sale_rate: (c_sale_rate_currrent - c_sale_rate_compare) * 100,
                c_gross_profit_rate: (c_gross_profit_rate_currrent - c_gross_profit_rate_compare) * 100,
                c_cost_inv: !compare.c_cost_inv ? 0 : (current.c_cost_inv - compare.c_cost_inv) / compare.c_cost_inv * 100,
                c_inv_days: !compare.c_inv_days ? 0 : (current.c_inv_days - compare.c_inv_days) / compare.c_inv_days * 100,
                c_perm: (c_perm_currrent - c_perm_compare),
            }
        }
    })

    adnoTableData2.value = list
}

const adnoSaleChartDataY2 = ref([])
const adnoSaleChartDataX2 = ref([]);
const adnoSaleChartStyle2 = ref("height: 1000rpx;background: #FFFFFF");
const adnoSaleChartOption2 = computed(() => {
    return {
        title: {
            text: ''
        },
        color: ['#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            triggerOn: 'click',
        },
        legend: {
            top: '0%',
            itemHeight: 8,
        },
        grid: {
            left: '0%',
            right: '0%',
            bottom: '3%',
            top: '4%',
            containLabel: true
        },
        xAxis: {
            boundaryGap: [0, 0.01],
            width: 20,
            splitLine: {
                show: false // 不显示网格线
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            axisLabel: {
                rotate: 45
            },
            type: 'value',
        },
        yAxis: {
            type: 'category',
            axisLabel: {
                rotate: 45
            },
            axisTick: {
                show: false // 不显示坐标轴刻度线
            },
            axisLine: {
                show: false, // 不显示坐标轴线
            },
            data: adnoSaleChartDataX2.value
        },
        series: adnoSaleChartDataY2.value,
    }
});

const formatAdnoSaleChartData2 = async (type = 'c_at_sale') => {
    adnoSaleChartDataY2.value = [];
    const amountType = type;
    let ids = [...currentAdnoSale2.value?.map(f => f.c_id), ...compareAdnoSale2.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);
    const list = ids.map(x => {
        const current = currentAdnoSale2.value.find(f => f.c_id == x) || {};
        const compare = compareAdnoSale2.value.find(f => f.c_id == x) || {};

        const c_sale_gradation = compare.c_at_sale == 0 ? 0 : ((current.c_at_sale - compare.c_at_sale) / compare.c_at_sale * 100 || 0).toFixed(2);
        const c_gross_profit_gradation = compare.c_gross_profit == 0 ? 0 : ((current.c_gross_profit - compare.c_gross_profit) / compare.c_gross_profit * 100 || 0).toFixed(2);

        return {
            title: getRelatedName("rdsDeparts", x) || x,
            current: { ...(calcUnit(current || { ...defaultSum })), c_sale_gradation: c_sale_gradation, c_gross_profit_gradation: c_gross_profit_gradation },
            compare: { ...(calcUnit(compare || { ...defaultSum })), c_sale_gradation: c_sale_gradation, c_gross_profit_gradation: c_gross_profit_gradation },
        }
    })

    //先从大到小排序，取前10个
    let sortedData = list.sort((a, b) => b.current[amountType] - a.current[amountType]).slice(0, 20);
    sortedData = list.sort((a, b) => a.current[amountType] - b.current[amountType]);
    const saleCurrentItemSort = sortedData.map(x => parseFloat(x.current[amountType]).toFixed(2));
    const saleCompareItemSort = sortedData.map(x => parseFloat(x.compare[amountType]).toFixed(2));
    adnoSaleChartDataX2.value = sortedData.map(x => x.title);
    adnoSaleChartDataY2.value.push({
        name: '本期',//+amountTypeOpts.find(f => f.value == amountType)?.text,
        type: 'bar',
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleCurrentItemSort,
        label: {
            show: true, // 显示标签
            distance: 3,
            borderWidth: 100,
            position: ['50%', '50%'], // 标签位置
            formatter: function (params) {
                if ([1, 2].includes(tabIndex4.value)) {
                    return numeral(params.data).format('0,0.00')
                } else {
                    return params.data + '%'
                }
            },
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
    if ([1, 2].includes(tabIndex4.value)) {
        adnoSaleChartDataY2.value.push({
            name: '对期',//+amountTypeOpts.find(f => f.value == amountType)?.text,
            type: 'bar',
            emphasis: {
                focus: 'none',
                disabled: true,
            },
            data: saleCompareItemSort,
            label: {
                show: true, // 显示标签
                distance: 3,
                borderWidth: 100,
                position: ['50%', '50%'], // 标签位置
                formatter: function (params) {
                    return numeral(params.data).format('0,0.00')
                },
                color: "#FFFFFF",
                lineHeight: 12,
                fontSize: 10,
                fontWeight: 100,
                align: 'center',
                verticalAlign: 'middle'
            }
        })
    }


    // 计算平均值
    const sum = saleCurrentItemSort.reduce((p, v) => Number(p) + Number(v), 0);
    const saleAvg = Array(saleCurrentItemSort.length).fill((sum / saleCurrentItemSort.length).toFixed(2));
    adnoSaleChartDataY2.value.push({
        name: '平均值',
        type: 'line',
        smooth: true,
        showSymbol: false,
        emphasis: {
            focus: 'none',
            disabled: true,
        },
        data: saleAvg,
        barWidth: '100%',
        lineStyle: {
            type: 'dashed' //虚线
        },
        label: {
            show: true, // 显示标签
            position: ['50%', '50%'], // 标签位置
            // 可以通过 formatter 自定义标签格式
            // formatter: bcnameList[i] + '\n' + '{c}' + '%', // {c} 表示数据值
            color: "#FFFFFF",
            lineHeight: 12,
            fontSize: 10,
            fontWeight: 100,
            align: 'center',
            verticalAlign: 'middle'
        }
    })
}

const abnormalSummaryData = ref({});
const queryAbnormalSummary = async () => {
    const objectData = {
        ...formData.value,
        c_store_id: formData.value.c_store_id,
        c_type: formData.value.c_type,
        c_level: formData.value.c_level,
        c_p_id: formData.value.c_p_id,
    }
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'QueryStoreAbnormalSummaryMBM', objectData, '881');
    abnormalSummaryData.value = result[0] || [];
}

const arrivalRateData = ref([]);
const queryArrivalRate = async () => {
    const objectData = {
        ...formData.value,
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_p_id: formData.value.c_p_id,
        c_id: formData.value.c_id,
    }
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'QueryStoreArrivalRateMBM', objectData, '881');
    arrivalRateData.value = result.map(x => {
        return {
            ...x,
            c_whole_arrive_rate: (x.c_whole_arrive_rate * 100).toFixed(2),
            c_pro_arrive_rate: (x.c_pro_arrive_rate * 100).toFixed(2),
            c_new_arrive_rate: (x.c_new_arrive_rate * 100).toFixed(2),
            c_whole_direction: (x.c_whole_direction * 100).toFixed(2),
            c_pro_direction: (x.c_pro_direction * 100).toFixed(2),
            c_new_direction: (x.c_new_direction * 100).toFixed(2),
            c_whole_promptly_arrive_rate: x.c_whole_promptly_arrive_rate > 1 ? 100 : (x.c_whole_promptly_arrive_rate * 100).toFixed(2),
            c_pro_promptly_arrive_rate: x.c_pro_promptly_arrive_rate > 1 ? 100 : (x.c_pro_promptly_arrive_rate * 100).toFixed(2),
            c_new_promptly_arrive_rate: x.c_new_promptly_arrive_rate > 1 ? 100 : (x.c_new_promptly_arrive_rate * 100).toFixed(2),
        }
    })[0];
}

//销售占比
const currentRateData = ref(0);
const compareRateData = ref(0);
const querySaleRate = async () => {
    const saletRateReq = {
        ...formData.value,
        c_store_id: formData.value.c_store_id,
        c_type: formData.value.c_type,
        c_level: formData.value.c_level,
    }

    let methodName = 'QueryManagerSaleRateMBM';
    if (formData.value.c_type == '10') {
        methodName = 'QueryManagerSaleRatePayTypeMBM';
    }
    const saleRateResult = await rdsRequest(rdsUrl.apiApi, '实时销售统计', methodName, saletRateReq, '881');
    currentRateData.value = saleRateResult?.currentData.map(x => {
        return {
            ...x,
            c_id: x.c_id === '0' ? '' : x.c_id,
        }
    });
    compareRateData.value = saleRateResult?.compareData.map(x => {
        return {
            ...x,
            c_id: x.c_id === '0' ? '' : x.c_id,
        }
    });;
    await formatSaleRateData(saletRateReq.c_type);
}

const rankColumn = ref([
    {
        title: '排名', // th标题
        isFixed: true, // 是否固定
        key: 'c_current_sale_rank', // 对应字段，
        align: 'center',
        width: 0.8, // 宽度 width * 100 rpx
    },
    {
        title: '名称', // th标题
        isFixed: true, // 是否固定
        key: 'c_name',
        align: 'left',
        width: 2,
    },
    {
        title: '排名变化', // th标题
        isFixed: false, // 是否固定
        key: 'c_rank_direction', // 对应字段
        align: 'right',
        width: 1,
        showIcon: true,
        showDirection: true,
        //slot: 'b' // 插槽名
    },
    {
        title: '销售金额', // th标题
        isFixed: false, // 是否固定
        key: 'c_at_sale', // 对应字段
        align: 'right',
        width: 1.8,
        precision: 2,
        //slot: 'c' // 插槽名
    },
    {
        title: '毛利额', // th标题
        isFixed: false, // 是否固定
        key: 'c_gross_profit',
        align: 'right',
        width: 1.5,
        precision: 2,
    },
    {
        title: '销量', // th标题
        isFixed: false, // 是否固定
        key: 'c_sale_count',
        align: 'right',
        width: 1.5,
    },
]);

//销售排名
const saleRankTableData = ref([]);
const querySaleStoreRankTable = async () => {
    const objectData = {
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
        c_rank_type: formData.value.c_rank_type,
    };
    let methodName = 'QueryStoreSaleRankCategoryMBM';
    if (formData.value.c_rank_type == '2') {
        methodName = 'QueryStoreSaleRankBrandMBM';
    } else if (formData.value.c_rank_type == '3') {
        methodName = 'QueryStoreSaleRankGoodsMBM';
    }
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', methodName, objectData, '881');
    result.map(x => {
        x.c_rank_direction = x.c_compare_sale_rank - x.c_current_sale_rank;
    })
    saleRankTableData.value = result;
    // await formatSaleRankTableData();
}
const formatSaleRankTableData = async () => {
}


const saleRateData = ref([]);
const formatSaleRateData = async (type) => {
    saleRateChartDataY.value = [];
    const amountType = 'c_at_sale';
    let ids = [...currentRateData.value?.map(f => f.c_id), ...compareRateData.value?.map(f => f.c_id)];
    ids = ids.filter((f, index) => ids.indexOf(f) == index);

    const list = ids.map(id => {
        const current = currentRateData.value.find(f => f.c_id == id);
        const compare = compareRateData.value.find(f => f.c_id == id);
        return {
            title: type == '6' ? mapChannel.value[id] || id || "其它" : type == '9' ? getDictName('经营方式', id) || id || "其它" : payCodeItems.value.find(x => x.value === id)?.name || id || "其它",
            current: calcUnit(current || { ...defaultSum }),
            compare: calcUnit(compare || { ...defaultSum })
        }
    })

    const currentSum = calcSum(currentRateData.value);
    const compareSum = calcSum(currentRateData.value);

    saleRateChartDataX.value = list.map(x => { return x.title });

    saleRateData.value = list.map(x => {
        return {
            name: x.title,
            title: x.title,
            value: x.current[amountType],
            compareValue: x.compare[amountType],
            rate: (((x.current[amountType] / currentSum[amountType]) * 10000) / 100).toFixed(2) + '%',
            upOrDown: x.current[amountType] - x.compare[amountType] > 0 ? true : false,
        }
    })

    // 按 value 降序排序
    saleRateData.value.sort((a, b) => b.value - a.value);
    //渠道为0是批发，汇入到其它里面
    const otherIndex = saleRateData.value.findIndex(item => item.name === "其它");

    if (saleRateData.value.length > 6) {
        let additionalValue = 0;
        // 计算下标大于 6 的元素的总和
        for (let i = 5; i < saleRateData.value.length; i++) {
            additionalValue += saleRateData.value[i].value;
        }
        if (otherIndex !== -1) {
            saleRateData.value[otherIndex].value += additionalValue;
        } else {
            saleRateData.value.push({ "name": "其它", "title": "其它", "rate": 0, "upOrDown": true, "value": additionalValue });
        }
        // 移除下标大于 6 的元素（除了 "其它" 元素）
        saleRateData.value.splice(5, saleRateData.value.length - 5 - 1);

    }
    const otherElement = saleRateData.value.splice(otherIndex !== -1 ? otherIndex : saleRateData.value.length - 1, 1)[0];
    if (otherElement) {
        const rate = (((otherElement.value / currentSum[amountType]) * 10000) / 100).toFixed(2) + '%';
        const otherCompareSum = saleRateData.value.reduce((p, v) => p + v.compareValue, 0);
        const otherCompare = compareSum[amountType] - otherCompareSum;
        saleRateData.value.push({ ...otherElement, rate: rate, upOrDown: otherElement.value - otherCompare > 0 });
    }

    // 计算数据总和
    var totalValue = saleRateData.value.reduce((sum, item) => sum + item.value, 0);

    saleRateChartDataY.value.push({
        name: currentSum[amountType],
        type: 'pie',
        radius: ['30%', '70%'],
        center: ['40%', '40%'], // 圆心位置
        avoidLabelOverlap: false,
        label: {
            show: false,
            position: 'center',
            fontSize: 10,
            formatter: '{b}: {c}'
        },
        emphasis: {
            label: {
                show: true,
                fontSize: 10,
                fontWeight: 'bold',
                formatter: function (param) {
                    return param.value.toFixed(2)// + '\n' + param.percent + '%';
                },
            }
        },
        labelLine: {
            show: false
        },
        data: saleRateData.value,
    })
}

const getCodeRuleLevel = async (c_type) => {
    // 获取部门层级
    // c_type === 'adno' : 'gdsclass';
    let result = [];
    const length = await rdsRequest(rdsUrl.scApi, '实时销售监测', 'GetCodeRuleLevel', c_type);
    if (length >= 0) {
        result = Array.from({ length: length }, (_, i) => ({ text: i + 1, value: i + 1 }));
    }
    return result;
}

// 获取系统参数、字典
const getSysConfig = async () => {
    sysConfig.value.adnoLevel = await getCodeRuleLevel('adno');
    sysConfig.value.adnoLevel.map(f => f.text = getUserDictName('部门层级', f.value + ''));
    sysConfig.value.gdsclassLevel = await getCodeRuleLevel('gdsclass');
    sysConfig.value.gdsclassLevel.map(f => f.text = getUserDictName('品类层级', f.value + ''));
    sysConfig.value.rentSaleIsRevenue = await getRdsSysConfig("进销存管理参数", "租赁商品销售是否记入销售收入") == '1';
}
// 设置默认值
const setDefault = async () => {
    const { loginInfo } = mainStore;
    sUserStore.value = loginInfo.sUserStore;
    sUserStoreName.value = loginInfo.sUserStoreName;
    sUser.value = loginInfo.sUser;
    formData.value.c_store_id = loginInfo.sUserStore;
}
//可比门店
const getCompareStore = async () => {
    const objectData = {
        c_sale_da: formData.value.c_sale_da,
        c_sale_da_en: formData.value.c_sale_da_en,
        c_sale_da2: formData.value.c_sale_da2,
        c_sale_da2_en: formData.value.c_sale_da2_en,
        c_store_id: formData.value.c_store_id,
    };
    const result = await rdsRequest(rdsUrl.apiApi, '实时销售统计', 'GetCompareStore', objectData, '881',);
    if (result.Result) {
        const storeList = result.Result[1].map(x => x.C_STORE_ID) || [];
        if (storeList.length > 0) {
            sUserStore.value = storeList[0];
            sUserStoreName.value = getRelatedName("rdsStores", storeList[0]);
            formData.value.c_store_id = storeList[0];
        } else {
            await setDefault();
        }
    }

}
onLoad(async (option) => {
    const jsonData = service.getLocalStorage("curSaleFormData");
    if (jsonData) {
        formData.value.c_unit_type = jsonData.c_unit_type;
        formData.value.c_adno_level = jsonData.c_adno_level;
        formData.value.c_class_level = jsonData.c_class_level;
    }

    if (dayjs().day() === 1) {
        currentTypeOpts[1].text = '上周/上上周';
    }
    if (dayjs().date() === 1) {
        currentTypeOpts[2].text = '上月/上上月';
    }

    await init();
    await getSysConfig();
    await getCompareStore();    
    await searchData();
})

const defaultSum = {
    c_at_sale_rate: 0,
    c_at_sale: 0,
    c_sale_value: 0,
    c_atv: 0,
    c_sale_count: 0,
    c_gross_profit: 0,
    c_gross_margin: 0,
    c_gross_profit_pro: 0,
    c_gross_margin_pro: 0,
    c_disc_value: 0,
    c_at_sale_mem: 0,
    c_at_sale_pro: 0,
    c_cost_inv: 0,
    c_inv_days: 0,
    c_gmroi: 0,
}

const calcSum = (items) => {
    const sum = (items || []).reduce((p, v) => {
        return {
            c_at_sale: p.c_at_sale + v.c_at_sale,
            c_sale_value: p.c_sale_value + v.c_sale_value,
            c_atv: 0,
            c_sale_count: p.c_sale_count + v.c_sale_count,
            c_gross_profit: p.c_gross_profit + v.c_gross_profit,
            c_gross_margin: p.c_gross_margin + v.c_gross_margin,
            c_gross_profit_pro: p.c_gross_profit_pro + v.c_gross_profit_pro,
            c_gross_margin_pro: p.c_gross_margin_pro + v.c_gross_margin_pro,
            c_disc_value: p.c_disc_value + v.c_disc_value,
            c_at_sale_mem: p.c_at_sale_mem + v.c_at_sale_mem,
            c_at_sale_pro: p.c_at_sale_pro + v.c_at_sale_pro,
            c_cost_inv: p.c_cost_inv + v.c_cost_inv,
            c_inv_days: p.c_inv_days + v.c_inv_days,
            c_gmroi: p.c_gmroi + v.c_gmroi,
        }
    }, { ...defaultSum });
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;

    sum.c_gross_margin = sum.c_at_sale == 0 ? 0 : sum.c_gross_profit / sum.c_at_sale * 100;
    sum.c_atv = sum.c_sale_count == 0 ? 0 : sum.c_at_sale / sum.c_sale_count;
    sum.c_at_sale = sum.c_at_sale / unit;
    sum.c_sale_value = sum.c_sale_value / unit;
    sum.c_gross_profit = sum.c_gross_profit / unit;
    sum.c_disc_value = sum.c_disc_value / unit;
    sum.c_at_sale_mem = sum.c_at_sale_mem / unit;
    sum.c_at_sale_pro = sum.c_at_sale_pro / unit;
    sum.c_cost_inv = sum.c_cost_inv / unit;
    sum.c_inv_days = sum.c_inv_days || 0;
    sum.c_gross_margin_pro = (sum.c_gross_margin_pro * 100) || 0;
    sum.c_gmroi = (sum.c_gmroi * 100) || 0;
    return sum;
}


const calcUnit = (item) => {
    const sum = { ...item }
    const unit = formData.value.c_unit_type == '1' ? 1 : 10000;
    sum.c_atv = sum.c_atv || 0;
    sum.c_at_sale = (sum.c_at_sale || 0) / unit;
    sum.c_sale_value = (sum.c_sale_value || 0) / unit;
    sum.c_gross_profit = (sum.c_gross_profit || 0) / unit;
    sum.c_disc_value = (sum.c_disc_value || 0) / unit;
    sum.c_gross_margin = (sum.c_gross_margin * 100) || 0;
    sum.c_cost_inv = (sum.c_cost_inv || 0) / unit;
    sum.c_inv_days = sum.c_inv_days || 0;
    return sum;
}

const customClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'reset':
            formData.value = {
                ...formData.value,
                c_current_type: '1', //本期
                c_sale_da: dayjs().format('YYYY-MM-DD'),
                c_sale_da_en: dayjs().format('YYYY-MM-DD'),
                c_sale_da2: dayjs().format('YYYY-MM-DD'),//对期
                c_sale_da2_en: dayjs().format('YYYY-MM-DD'),//对期
                c_is_compare: true,
                c_type: '1', //1-机构, 2-部门, 3-品类
                c_level: 1,
                c_store_id: mainStore.loginInfo.sUserStore,
                c_p_id: '',
                c_adno_level: 1,
                c_class_level: 1,
                c_unit_type: '1',
            };
            service.removeStorageSync('curSaleFormData');
            service.addlocalStorage('curSaleFormData', { c_unit_type: formData.value.c_unit_type, c_adno_level: formData.value.c_adno_level, c_class_level: formData.value.c_class_level, c_day_period: formData.value.c_day_period });
            break;
        case 'fix':
            customPopup.value.close();
            service.removeStorageSync('curSaleFormData');
            service.addlocalStorage('curSaleFormData', { c_unit_type: formData.value.c_unit_type, c_adno_level: formData.value.c_adno_level, c_class_level: formData.value.c_class_level, c_day_period: formData.value.c_day_period });
            if (formData.value.c_type == '2') {
                formData.value.c_level = formData.value.c_adno_level;
            } else if (formData.value.c_type == '3') {
                formData.value.c_level = formData.value.c_class_level;
            }
            console.log("showColumn.value", showColumn.value)
            await searchData();
            break;
    }
};

const clickDetail = () => {
    const { c_sale_da, c_sale_da_en, c_sale_da2, c_sale_da2_en, c_store_id, c_current_type, c_type, c_level, c_unit_type } = formData.value;
    uni.navigateTo({
        url: `./detail?c_sale_da=${c_sale_da}&c_sale_da_en=${c_sale_da_en}&c_sale_da2=${c_sale_da2}&c_sale_da2_en=${c_sale_da2_en}&c_store_id=${c_store_id}&c_current_type=${c_current_type}&c_type=${c_type}&c_level=${c_level}&c_unit_type=${c_unit_type}`,
    });
}

const buttonClick = async (e) => {
    const { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'reset':
            formData.value = {
                ...formData.value,
                c_sale_da: dayjs().format('YYYY-MM-DD'),
                c_sale_da_en: dayjs().format('YYYY-MM-DD'),
                c_sale_da2: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),//对期
                c_sale_da2_en: dayjs().subtract(1, 'days').format('YYYY-MM-DD'),//对期
            };
            break;
        case 'fix':
            searchPopup.value.close()
            await searchData();
            break;
        case 'close':
            storePopup.value.close()
            break;
    }
};

// 系统参数，字典
const sysConfig = ref({
    adnoLevel: [],
    gdsclassLevel: [],
    rentSaleIsRevenue: false,
})

onMounted(() => {
    getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
    await uni.getSystemInfo({
        success: function (res) { // res - 各种参数
            let info = uni.createSelectorQuery().select(".footer-view");
            info.boundingClientRect(function (data) { //data - 各种参数
                //获取列表高度
                let height = res.windowHeight - data.top;
                //转换rpx
                let finalHeight = height / (res.windowWidth / 750) - 100;
                listHeight.value = finalHeight;
                oriHeight.value = finalHeight;
            }).exec()
        }
    });
};
// 点击navbar右侧图标
const clickNavbarRight = () => {
    customPopup.value.open();
}

const showAdnoSale = ref(false);
const cardAdnoName = ref('');
const clickAdnoCell = async (index, item) => {
    if (item.current.c_adno_name == '全部部门') {
        cardAdnoName.value = '';
        // formData.value.c_p_id = '';
        return
    }
    console.log("index,item", index, item)
    service.enjoyShowLoading("正在加载...");
    showAdnoSale.value = true;
    cardAdnoName.value = '-' + item.current.c_adno_name;
    formData.value.c_p_id = item.current.c_id;
    await queryAdnoSale2();
    await queryAbnormalSummary();
    await queryArrivalRate();
    service.enjoyHideLoading();
}
const clickAdnoSale = () => {
    tabIndex4.value = 0;
    showAdnoSale.value = !showAdnoSale.value;
}

const jumpCurSale = () => {
    service.enjoyShowLoading("正在跳转...");
    setTimeout(() => {
        uni.navigateTo({
            url: './index',
        });
    }, 500);
    service.enjoyHideLoading();
}

// 选择框点击事件
const clickStore = () => {
    let parms = Enjoy.GetDialogParms();
    parms.CallBack = SelectionChanged;
    parms.SelectionType = "机构选择";
    parms.SelectedItems = sUserStore.value;
    parms.WhereList = [{ c_col: "c_type", c_oper: "等于", c_value: '2', c_logic: "而且" }];
    Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (event) => {
    if (event.SelectionType == '机构选择') {
        // 更新机构信息
        sUserStoreName.value = event.BackParms.Value;
        sUserStore.value = event.BackParms.Key;
        // 按新条件获取数据
        formData.value.c_store_id = sUserStore.value;
        await updateStoreType();
    }
    // 按新条件获取数据
    await searchData();
}

</script>

<style lang="scss" scoped>
@import '@/main.scss';
@import '@/static/font/enjoyicon/iconfont.css';
@import '@/static/font/menu/iconfont.css';

.content {
    background-color: #F4F4F4;
    display: flex;
    padding: 0;
    width: 100%;
}

.content-img {
    background: pink;
    background-size: 100% 150px;
    background-repeat: no-repeat;
    flex: 1;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: stretch;
}

.navigation {
    flex: 0 0 auto;
    margin-bottom: 5px;
}

.main-view {
    width: 100%;
    height: auto;
    background: #00aaff;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.footer-view {
    width: 100%;
    flex: 1;
    box-sizing: border-box;
    margin-top: 16rpx;
    display: flex;
}

// start 重置标题栏右侧样式 展示当前用户所属门店
::v-deep .uni-navbar__header-btns-right {
    position: relative;
    height: 100%;
}

::v-deep .uni-nav-bar-right-text {
    position: absolute;
    top: 0;
    right: 0;
    color: #aaffff;
    text-align: center;
    max-width: 200rpx;
    margin-right: 30rpx;
    font-size: 0.8rem;
    padding-top: 0.1rem;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// end  重置标题栏右侧样式 展示当前用户所属门店

.scroll-box {
    height: 100%;
}

// 日期选择
.search-bar {
    background: #FFFFFF;
    display: flex;
    justify-content: space-around;
    flex: 0 0 auto;
    padding: 10rpx 0 0 0;

    .left,
    .right,
    .center {
        display: flex;
        align-items: flex-start;
        justify-content: space-around;
        flex-direction: column;

        // 重置日期选择组件内的显示文字大小
        ::v-deep .uni-date-x {
            background-color: transparent;
        }

        ::v-deep .uni-date__x-input {
            font-size: 32rpx !important;
            font-weight: bold;
            background: transparent;
            border-bottom: 1px solid rgba(30, 30, 30, 0.1);
        }

        checkbox-group {
            display: flex;
            flex-direction: column;
            gap: 10rpx;
            padding: 10rpx 0;
        }

        label {
            color: #626262;
        }
    }

    .left,
    .right {
        padding: 10rpx 0;

        label {
            font-size: 0.6rem;
            margin: 0;
            padding: 0;
            line-height: 1rem;
        }

    }

    .left {
        ::v-deep .uni-date__x-input {
            color: #4090f7;
        }
    }

    .right {
        ::v-deep .uni-date__x-input {
            color: #9ec87d;
        }
    }

}

// 数据展示
.data-box {
    margin: 0 20rpx 20rpx 20rpx;
    padding: 0 $uni-spacing-row-base;
    background-color: #FFFFFF;
    border-radius: 20rpx;
    display: flex;
    flex-wrap: wrap;

}

// 数据展示
.data-title {
    margin: 0 20rpx 20rpx 20rpx;
    padding: 0 $uni-spacing-row-base;
    display: flex;
    flex-wrap: wrap;

}


// 机构，部门，品类 曲线图 切换
.chart-box {
    background: #ffffff;
    padding-top: 20rpx;

    .chart-ctrl {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin: 0 20rpx;
        padding: 20rpx 0;

        .levelBox {
            flex: 0 0 25%;
            margin: 0 10rpx;
            padding: 0;
            border-bottom: 1px solid rgba(30, 30, 30, 0.1);

            ::v-deep .m-input-input-left {
                text-align: center;
                font-weight: bold;
                line-height: 1.2rem;
            }

            ::v-deep .m-card-arrowright {
                font-size: $uni-font-size-base !important;
            }
        }

        .switch-tab {
            flex: 0 0 72%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            background-color: #E3E3E3;
            padding: 6rpx;
            box-sizing: border-box;
            border-radius: 10rpx;
            height: 72rpx;

            .active,
            .normal {
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 10rpx;
                width: 50%;
                height: 100%;
                font-weight: bold;
            }

            .active {
                color: #000;
                background-color: #fff;
            }

            .normal {
                color: #515151;
            }
        }


    }

}

// 表格
.table-view {
    height: 500rpx;
    background: #ffffff;
    margin: 20rpx;
}

.table-text {
    font-size: 22rpx;
    margin: 10rpx;
}

.bottom {
    display: flex;
    justify-content: space-between;
    flex: 0 0 auto;
    height: 70rpx;
    padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
    background: $uni-bg-color;
    margin-bottom: 2px;
}


// start 自定义更多按钮
// 复制 RdsNavBar
.custom-menu {
    border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    justify-content: flex-start;
}

.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// 业务自定义
.icon_new_count {
    color: #00aaff;
}

// end 自定义更多按钮

// start 查询筛选
.search-fields {
    width: 100%;

    .center {
        margin: 0 10px;
    }

    uni-button {
        font-size: 16px;
        line-height: 40px;
    }

    .search-field {
        margin: 5px 0;
        padding: 5px 0;
        font-size: 18px;
    }

    ::v-deep .m-card-input-content,
    ::v-deep .m-input-input {
        height: 100%;
        text-align: right !important;

        uni-view,
        * {
            font-size: 16px;
            margin: 0 !important;
        }
    }

    .bottom {
        background: #ffffff;
        margin: 5px 0px 0px;
        padding: 5px 0;
        border-top: 1px solid #cccccc;
    }
}

// end 查询筛选

// 列表项自定义
.custom-id {
    z-index: 1;
    position: relative;
    line-height: 1.2em;
}

.custom-id::before {
    position: absolute;
    z-index: 0;
    content: ' ';
    width: 2.5em;
    height: 1.2em;
    background: rgba(153, 255, 102, 0.2);
    top: 0;
    left: 0;
}

// end 列表项自定义
.stylePriv1 {
    color: #333333 !important;
}

.stylePriv2 {}

.flex-item {
    flex: 1 1 50%;
}

.selector-view {
    width: 100%;
    height: auto;
    background: #FFFFFF;
    display: flex;
    flex-direction: row;
    padding: 15rpx;
}

.levelBox {
    flex: 0 0 25%;
    margin: 0 10rpx;
    padding: 0;
    border-bottom: 1px solid rgba(30, 30, 30, 0.1);

    ::v-deep .m-input-input-left {
        text-align: center;
        font-weight: bold;
        line-height: 1.2rem;
    }

    ::v-deep .m-card-arrowright {
        font-size: $uni-font-size-base !important;
    }
}

.center-view {
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: row;
    background: #ffffff;
    padding: 15rpx;
}

.tips-text {
    margin-left: 20rpx;
    color: $uni-text-color-grey;
}

.item-view {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    align-items: center;
    margin-top: 16rpx;
    row-gap: 8rpx;
}

.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 40% 59%;
    font-size: 12px;
}

.rate-view {
    width: 100%;
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 33.33%;
    font-size: 24rpx;
}

.rate-card {
    margin: 2rpx;
    border-radius: 10rpx;
    background-color: rgb(249, 249, 249);
    padding: 2rpx;
}

.rank-card {
    margin: 4rpx;
    border-radius: 10rpx;
    background-color: rgb(249, 249, 249);
    padding: 4rpx;
}


.bt-button {
    background-color: #FFFFFF;
    padding: 10rpx 0rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}


.popup-content {
    align-items: center;
    justify-content: flex-start;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    // height: 600rpx;
    // overflow-y: scroll;
}


.image-min {
    width: 100%;
    height: 150rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
    margin-top: -20rpx;
}

.popup-height {
    width: 200px;
}

.popup-content-message {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
    width: 100%;
    height: 84rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: $uni-text-color-secondary;
    font-size: $uni-font-size-level1;
    line-height: 45rpx;
    text-align: center;
    position: relative;
}


.m-card-input-view2 {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;
    height: 122rpx;
    background: $uni-bg-color-inverse;
    box-sizing: border-box;
    border-bottom: 1rpx solid #EEEEEE;
}

.m-card-input-title2 {
    width: 185rpx;
    height: 40rpx;
}

.m-title-text2 {
    font-size: $uni-font-size-level3;
    font-family: $uni-font-family;
    font-weight: $uni-font-weight-level1;
    color: $uni-text-color-title;
    line-height: 40rpx;
    text-align: left;
    font-style: normal;
}

.time-view {
    display: flex;
    flex-direction: column;
}

.time-top {
    font-size: $uni-font-size-level2;
    font-family: $uni-font-family;
    color: $uni-text-color-primary;
    line-height: 30rpx;
    text-align: left;
    font-style: normal;
}


.heng-view {
    width: 28rpx;
    height: 2rpx;
    background: $uni-text-color-weak;
    margin: 40rpx;
}

.swiper {
    height: 400rpx;
}
</style>